from django import forms
from django.db.models import Q

from apps.BaseForm import FormMixin
from apps.app_post.models import Post, Category, Tag


class PostForm(forms.ModelForm, FormMixin):
    category = forms.IntegerField(required=True)
    is_recom = forms.IntegerField(required=True)

    class Meta:
        model = Post
        fields = ('title', 'desc', 'content', 'thumbnail', 'is_recom', 'category')
        error_messages = {
            "title": {
                "require": '标题必填',
                "max_length": '标题不能超出 100 字符',
            },
            "desc": {
                "require": '描述必填',
                "max_length": '描述不能超出 300 字符',
            },
            "category": {
                "require": '分类必填',
            },
            "thumbnail": {
                "require": '封面图必填',
            },
        }

    def clean_category(self):
        category_id = self.cleaned_data.get('category')
        try:
            category = Category.objects.get(pk=category_id)
        except Category.DoesNotExist:
            raise forms.ValidationError('该分类不存在~~')
        return category


class CategoryForm(forms.ModelForm, FormMixin):
    class Meta:
        model = Category
        fields = ('name',)
        error_messages = {
            "name": {
                "require": '分类必填',
                "max_length": '分类不能超出 20 字符',
            },
        }

    def clean_name(self):
        name = self.cleaned_data.get('name')
        category = Category.objects.filter(name=name)
        if category.exists():
            raise forms.ValidationError('该分类已存在~~')
        return name


class TagForm(forms.ModelForm, FormMixin):
    class Meta:
        model = Tag
        fields = ('name',)
        error_messages = {
            "name": {
                "require": '标签名必填',
                "max_length": '标签名不能超出 20 字符',
            },
        }

    def clean_name(self):
        name = self.cleaned_data.get('name')
        tag = Tag.objects.filter(name=name)
        if tag.exists():
            raise forms.ValidationError('该标签已存在~~')
        return name
